package com.wanmait.heating.filter;

import com.wanmait.heating.pojo.Userinfo;
import com.wanmait.heating.service.UserinfoService;
import com.wanmait.heating.utils.CookieUtils;
import com.wanmait.heating.utils.EncryptUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter({"/web/*","/user/usercenter"})
public class UserinfoAutoLoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        Userinfo loginUser = (Userinfo)session.getAttribute("loginUser");


        //查看是否登录
        if(loginUser == null)
        {
            //读取cookie查看是否记住我
            String name = CookieUtils.read("name", request);
           ;
            if(name!=null)//记住我
            {
                //对用户名进行解密
                name = EncryptUtils.decrypt(name, 3);
                String password = CookieUtils.read("password", request);

                //登录检查
                ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
                UserinfoService userinfoService = applicationContext.getBean("userinfoService",UserinfoService.class);
                Userinfo userinfo = new Userinfo();
                userinfo.setName(name);
                userinfo.setPassword(password);
                Userinfo userinfox = userinfoService.isExist(userinfo);
                //重新自动登录
                if(userinfox != null){
                    session.setAttribute("loginUser", userinfox);
                    session.setMaxInactiveInterval(60*60*24*30);
                    //写cookie
                    CookieUtils.write("name", EncryptUtils.encrypt(userinfo.getName(), 3), "/", 60 * 60 * 24 * 30, response);
                    CookieUtils.write("password", userinfo.getPassword(), "/", 60 * 60 * 24 * 30, response);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
